package gold.digger;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC856 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int scoreOfParentheses(String s) {
            Stack<String> stack = new Stack<>();
            for (int i = 0; i < s.length(); i++) {
                if ('(' == s.charAt(i)) {
                    stack.push("(");
                } else {
                    int curSum = 0;
                    while (!stack.isEmpty() && Character.isDigit(stack.peek().charAt(0))) {
                        //栈中已经含有数字，遇到右括号需要弹出栈中所有数字的和，再乘以2
                        curSum += Integer.parseInt(stack.pop());
                    }
                    if (0 == curSum) {
                        //当前和为0，说明栈中无数字，只有左括号
                        if (!stack.isEmpty()) {
                            stack.pop();
                            stack.push("1");
                        } else {
                            System.out.println("error here.");
                        }
                    } else {
                        if (!stack.isEmpty()) {
                            stack.pop();
                        }
                        stack.push(String.valueOf(curSum * 2));
                    }
                }
            }

            int sum = 0;
            while (!stack.isEmpty()) {
                sum += Integer.parseInt(stack.pop());
            }

            return sum;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.scoreOfParentheses("(()(()))"));
    }

    public static void main(String[] args) throws Exception {
        LC856 an = new LC856();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
